package com.ruoyi.web.controller.smy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.BanquetConstants;
import com.ruoyi.common.constant.UserType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.smy.MallMerchantPersonalInfo;
import com.ruoyi.common.core.domain.smy.MallOrder;
import com.ruoyi.common.core.domain.smy.MallOrderDetail;
import com.ruoyi.common.core.domain.smy.SecurityWebUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.dto.OptDto;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exportDto.MallOrderDto;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.smy.IMallMerchantPersonalInfoService;
import com.ruoyi.system.service.smy.IMallOrderDetailService;
import com.ruoyi.system.service.smy.IMallOrderService;
import com.ruoyi.system.service.smy.ISecurityWebUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/smy/mallOrder")
public class MallOrderController extends BaseController {
	@Resource
	private IMallOrderService mallOrderService;

	@Resource
	private IMallOrderDetailService orderDetailService;

	@Resource
	private ISecurityWebUserService userService;

	@Resource
	private IMallMerchantPersonalInfoService personalInfoService;

	@Resource
	private ISysRoleService roleService;

	@Value("${app.baseUrl}")
	private String appBaseUrl;

	@Value("${microApp.imageUrl}")
	private String microImageUrl;

	@GetMapping("/list")
	public TableDataInfo list(MallOrder mallOrder) {
		SysUser user = SecurityUtils.getLoginUser().getUser();
		if(roleService.checkHaveRole(user.getRoles(), UserType.QYJMS)){
			StringBuffer joinArea = new StringBuffer("%");
			if(Objects.nonNull(user)){
				if(StrUtil.isNotEmpty(user.getProvinceName())){
					joinArea.append(user.getProvinceName());
				}
				if(StrUtil.isNotEmpty(user.getCityName()) && !StrUtil.equals("全部",user.getCityName())){
					joinArea.append(user.getCityName());
				}
				if(StrUtil.isNotEmpty(user.getCountyName()) && !StrUtil.equals("全部",user.getCountyName())){
					joinArea.append(user.getCountyName());
				}
			}
			joinArea.append("%");
			mallOrder.setJoinArea(joinArea.toString());
		}
		//校验用户是否为商家，如果是商家则只显示此商家的订单
		if(roleService.checkHaveRole(user.getRoles(), UserType.COMMON_MERCHANT)){
			SecurityWebUser queryDto = new SecurityWebUser();
			queryDto.setMobile(user.getPhonenumber());
			queryDto.setRoleId(4L);
			List<SecurityWebUser> webUserList = userService.selectSecurityWebUserList(queryDto);
			if(CollectionUtil.isNotEmpty(webUserList)){
				SecurityWebUser merchant = webUserList.get(0);
				mallOrder.setMerchantId(merchant.getId());
			}
		}
		startPage();
		List<MallOrder> list = mallOrderService.selectMallOrderPage(mallOrder);
		return getDataTable(list);
	}

	/**
	 * 导出【请填写功能名称】列表
	 */
	@PreAuthorize("@ss.hasPermi('smy:order:export')")
	@Log(title = "订单导出", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, MallOrder mallOrder) {
		List<MallOrder> list = mallOrderService.selectMallOrderList(mallOrder);
		List<MallOrderDto> orderDtoList = CollectionUtil.newArrayList();
		for(MallOrder order : list){
			List<MallOrderDto> singleOrderDtoList = buildOrderDtoList(order);
			orderDtoList.addAll(singleOrderDtoList);
		}
		ExcelUtil<MallOrderDto> util = new ExcelUtil<>(MallOrderDto.class);
		util.exportExcel(response, orderDtoList, "订单导出");
	}

	/**
	 * 拼装导出集合信息
	 * @param order
	 * @return
	 */
	private List<MallOrderDto> buildOrderDtoList(MallOrder order) {
		MallOrderDetail queryDto = new MallOrderDetail();
		queryDto.setOrderId(order.getId());
		List<MallOrderDetail> detailList = orderDetailService.selectMallOrderDetailList(queryDto);
		SecurityWebUser merchant = userService.selectSecurityWebUserById(order.getMerchantId());
		SecurityWebUser member = userService.selectSecurityWebUserById(order.getMemberId());
		MallMerchantPersonalInfo personalInfo = null;
		if(Objects.nonNull(merchant)){
			personalInfo = personalInfoService.selectMallMerchantPersonalInfoById(merchant.getMerchantpersonalinfoId());
		}
		List<MallOrderDto> resultList = CollectionUtil.newArrayList();
		if(CollectionUtil.isNotEmpty(detailList)){
			for (MallOrderDetail detail : detailList) {
				MallOrderDto dto = new MallOrderDto();
				BeanUtil.copyProperties(order, dto);
				if(Objects.nonNull(personalInfo)){
					dto.setMerchantName(personalInfo.getCookername());
				}
				if(Objects.nonNull(merchant)){
					dto.setMerchantPhone(merchant.getMobile());
				}
				if(Objects.nonNull(member)){
					dto.setMemberName(member.getNickname());
					dto.setMemberPhone(member.getMobile());
				}
				dto.setGoodsName(detail.getGoodsname());
				dto.setUnitprice(detail.getUnitprice());
				dto.setGoodsQty(detail.getQuantity());
				resultList.add(dto);
			}
		}
		if(!StrUtil.equals("room",order.getOrdertype())){
			MallOrderDto dto = new MallOrderDto();
			BeanUtil.copyProperties(order, dto);
			if(Objects.nonNull(personalInfo)){
				dto.setMerchantName(personalInfo.getCookername());
			}
			if(Objects.nonNull(merchant)){
				dto.setMerchantPhone(merchant.getMobile());
			}
			if(Objects.nonNull(member)){
				dto.setMemberName(member.getNickname());
				dto.setMemberPhone(member.getMobile());
			}
			if(StrUtil.equals("Y",order.getEattoday())){
				dto.setGoodsName("即点即吃");
			}
			resultList.add(dto);
		}
		return resultList;
	}

	/**
	 * 获取【请填写功能名称】详细信息
	 */
	@PreAuthorize("@ss.hasPermi('smy:order:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(mallOrderService.selectMallOrderById(id));
	}

	/**
	 * 新增【请填写功能名称】
	 */
	@PreAuthorize("@ss.hasPermi('smy:order:add')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody MallOrder mallOrder) {
		return toAjax(mallOrderService.insertMallOrder(mallOrder));
	}

	/**
	 * 修改【请填写功能名称】
	 */
	@PreAuthorize("@ss.hasPermi('smy:order:edit')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody MallOrder mallOrder) {
		return toAjax(mallOrderService.updateMallOrder(mallOrder));
	}

	/**
	 * 删除【请填写功能名称】
	 */
	@PreAuthorize("@ss.hasPermi('smy:order:remove')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(mallOrderService.deleteMallOrderByIds(ids));
	}


	@PreAuthorize("@ss.hasPermi('smy:order:audit')")
	@Log(title = "审核订单", businessType = BusinessType.UPDATE)
	@PostMapping(value = "/audit")
	public AjaxResult auditOrder(@RequestBody OptDto optDto) {
		try {
			if(StrUtil.isNotEmpty(optDto.getOptId())){
				MallOrder mallOrder = mallOrderService.selectMallOrderById(Long.valueOf(optDto.getOptId()));
				if(Objects.nonNull(mallOrder)){
					if(StrUtil.equals(BanquetConstants.YES,optDto.getOptType())){
						mallOrderService.confirmOrder(appBaseUrl,microImageUrl,mallOrder);
					}
					if(StrUtil.equals(BanquetConstants.NO,optDto.getOptType())){
						mallOrderService.cancelOrder(mallOrder);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}

	@PreAuthorize("@ss.hasPermi('smy:order:audit')")
	@Log(title = "审核订单", businessType = BusinessType.UPDATE)
	@PostMapping(value = "/auditAndSend")
	public AjaxResult auditAndSend(@RequestBody MallOrder mallOrder) {
		try {
			mallOrderService.confirmOrder(appBaseUrl,microImageUrl,mallOrder);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}

	@PreAuthorize("@ss.hasPermi('smy:order:detail')")
	@Log(title = "查询订单详情", businessType = BusinessType.OTHER)
	@GetMapping(value = "/detail/{id}")
	public AjaxResult getOrderDetail(@PathVariable("id") Long id) {
		return AjaxResult.success(mallOrderService.getOrderDetail(id));
	}
}
